package com.mukefile.service.impl;

import com.mukefile.dao.UploadDao;
import com.mukefile.data.bo.FileBo;
import com.mukefile.pojo.ActualFile;
import com.mukefile.pojo.UserFile;
import com.mukefile.service.SysProfileService;
import com.mukefile.service.UploadService;
import com.mukefile.utils.CommonUtil;
import com.mukefile.utils.constant.Constant;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @author xinke.huang@hand-china.com
 * @version 1.0
 * @date 2021/2/11
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UploadServiceImpl implements UploadService {
    @Resource
    UploadDao uploadDao;
    @Resource
    SysProfileService sysProfileService;
    @Override
    public void uploadFile(FileBo fileBo) throws IOException {
        // 文件存储路径
        String actualPath = sysProfileService.getSysProfileValue(Constant.ACTUAL_PATH);
        // 修改用户表,设置磁盘已用空间

        // 插入一条实际文件数据
        ActualFile actualFile = new ActualFile();
        // 获取文件扩展名
        String fileExtension = CommonUtil.getFileExtension(fileBo.getKnsFile().getName());
        actualFile.setFilename(fileBo.getKnsFile().getUuid() + fileExtension);
        actualFile.setFileByte(fileBo.getKnsFile().getFile().length());
        actualFile.setCreateDate(new Date());
        // 插入一条用户文件记录
        UserFile userFile = new UserFile();
        userFile.setFilename(fileBo.getKnsFile().getName());
        userFile.setFolderId(fileBo.getFolderId());
        userFile.setUserId(fileBo.getUserId());
        userFile.setType(Constant.FILE);
        userFile.setUpdateTime(new Date());
        userFile.setDeleted("N");
        // 执行插入
        this.uploadDao.insetFile(actualFile,userFile);

        // 将文件上传至本地磁盘
        FileUtils.copyFile(
                fileBo.getKnsFile().getFile(),
                new File(actualPath + actualFile.getFilename()));


    }
}
